#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include "comm.hpp"

int main()
{
    umask(0);
    int n = mkfifo(filename.c_str(), mode);
    if (n != 0)
    {
        std::cout << errno << ": " << strerror(errno) << std::endl;
        return 1;
    }
    std::cout << "create fifo success, begin ipc" << std::endl;

    int rfd = open(filename.c_str(), O_RDONLY);
    if (rfd < 0)
    {
        std::cout << errno << ": " << strerror(errno) << std::endl;
        return 2;
    }
    std::cout << "open fifo success, begin ipc" << std::endl;

    char buffer[NUM];
    while (true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer)-1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            // printf("%c", buffer[0]);
            // fflush(stdout);
        }
        else if  (n == 0)
        {
            std::cout << "client quit, me too" << std::endl;
            break;
        }
        else
        {
            std::cout << errno << ": " << strerror(errno) << std::endl;
            break;
        }
    }

    close(rfd);

    unlink(filename.c_str());
    return 0;
}